package com.hup.utils.swing.customView.spinner;

import com.hup.utils.commons.start.LookThemeUtil;
import com.hup.utils.swing.DimensionUtil;
import lombok.Getter;

import javax.swing.*;
import java.awt.*;

/**
 * 兼容缩放的Spinner;
 * {@link JSpinner}通过 {@link UIManager}只能修复按钮的缩放,不能修复字体缩放
 * @author hugan
 * @date 2020/4/7
 */
public class BaseNumSpinner extends JSpinner {

    /**
     * 按数字个数衡量 的控件[最小和最优]宽度
     */
    @Getter
    private int minCharColumn = 8;

    public BaseNumSpinner() {
        this(new SpinnerNumberModel());
    }

    public BaseNumSpinner(SpinnerModel model) {
        super(model);
        Font old = getFont();
        Font font = new Font(old.getName(), old.getStyle(), (int) (old.getSize() * LookThemeUtil.getScreenScale()));
        super.setFont(font);
        resize();
    }

    public void setMinCharColumn(int minCharColumn) {
        this.minCharColumn = minCharColumn;
        resize();
    }

    @Override
    public void setFont(Font font) {
        super.setFont(font);
        resize();
    }

    public void resize() {
        if (minCharColumn == 0) {
            return;//首次实例化时会是0,如果不过滤:会导致maxSize是0,继而时view展示后没高度
        }
        Dimension charWidth = DimensionUtil.getSizeOfNumber(getFont(), "0");
        Dimension preferredSize = getPreferredSize();
        preferredSize.width = charWidth.width * minCharColumn;
        setMinimumSize(preferredSize);
        setPreferredSize(preferredSize);
    }

}
